import React, { useState, useEffect } from 'react';
import { Card, Descriptions, Button, Spin, message, Tag } from 'antd';
import { ArrowLeftOutlined, EditOutlined } from '@ant-design/icons';
import { history, useParams } from '@umijs/max';
import type { CategoryItem } from '@/types/category';
import { getCategoryDetail } from '@/services/categoryApi';

const CategoryDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [category, setCategory] = useState<CategoryItem | null>(null);
  const [loading, setLoading] = useState(false);

  // 获取分类详情
  const fetchCategoryDetail = async () => {
    if (!id) return;

    setLoading(true);
    try {
      const res = await getCategoryDetail(Number(id));
      setCategory(res);
    } catch (error) {
      message.error('获取分类详情失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCategoryDetail();
  }, [id]);

  // 编辑分类
  const handleEdit = () => {
    history.push(`/categories/edit/${id}`);
  };

  if (loading) {
    return <div style={{ padding: 24, textAlign: 'center' }}><Spin size="large" /></div>;
  }

  if (!category) {
    return <div>分类不存在</div>;
  }

  return (
    <div>
      <Card style={{ marginBottom: 16 }}>
        <Button 
          icon={<ArrowLeftOutlined />} 
          onClick={() => history.push('/categories/list')}
          style={{ marginRight: 8 }}
        >
          返回列表
        </Button>
        <Button 
          type="primary" 
          icon={<EditOutlined />} 
          onClick={handleEdit}
        >
          编辑分类
        </Button>
      </Card>

      <Card title="分类详情">
        <Descriptions bordered column={2}>
          <Descriptions.Item label="分类名称">{category.name}</Descriptions.Item>
          <Descriptions.Item label="父级分类">
            {category.parent ? category.parent.name : '无'}
          </Descriptions.Item>
          <Descriptions.Item label="描述">{category.description || '无'}</Descriptions.Item>
          <Descriptions.Item label="创建时间">{category.created_at}</Descriptions.Item>
          <Descriptions.Item label="更新时间">{category.updated_at}</Descriptions.Item>
        </Descriptions>
      </Card>

      {category.children && category.children.length > 0 && (
        <Card title="子分类" style={{ marginTop: 16 }}>
          {category.children.map(child => (
            <Tag 
              key={child.id} 
              onClick={() => history.push(`/categories/detail/${child.id}`)}
              style={{ cursor: 'pointer', marginBottom: 8 }}
            >
              {child.name}
            </Tag>
          ))}
        </Card>
      )}
    </div>
  );
};

export default CategoryDetail;